/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.Resource;
import me.zhengjie.modules.system.domain.ResourceNum;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.UserQueryCriteria;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.ResourceService;
import me.zhengjie.modules.system.domain.vo.ResourceQueryCriteria;
import me.zhengjie.modules.system.mapper.ResourceMapper;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.mapper.TeacherMapper;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-05-04
**/
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    private final ResourceMapper resourceMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    //获取该学校资源数量
    @Override
    public ResourceNum querySchoolResourceNum(){

        User user = userMapper.selectById(SecurityUtils.getCurrentUserId());

        ResourceNum resourceNum = new ResourceNum();
        QueryWrapper queryWrapper1 = new QueryWrapper<Resource>();
        queryWrapper1.eq("type",0);
        queryWrapper1.eq("schoolId", user.getDeptId());

        resourceNum.setImgNum(Math.toIntExact(resourceMapper.selectCount(queryWrapper1)));

        QueryWrapper queryWrapper2 = new QueryWrapper<Resource>();
        queryWrapper2.eq("type",2);
        queryWrapper2.eq("schoolId", user.getDeptId());
//        resourceMapper.selectCount(queryWrapper2);
        resourceNum.setVideoNum(Math.toIntExact(resourceMapper.selectCount(queryWrapper2)));

        QueryWrapper queryWrapper3 = new QueryWrapper<Resource>();
        queryWrapper3.eq("type",6);
        queryWrapper3.eq("schoolId", user.getDeptId());
//        resourceMapper.selectCount(queryWrapper3);
        resourceNum.setFileNum(Math.toIntExact(resourceMapper.selectCount(queryWrapper3)));

        return resourceNum;
    }
    @Override
    public PageResult<Resource> queryAll(ResourceQueryCriteria criteria, Page<Object> page){
        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        List<User> userList = userMapper.findAll(userQueryCriteria);

        IPage<Resource> resourceList = resourceMapper.findAll(criteria, page);
        for(Resource resource:resourceList.getRecords()){
            for(User user:userList){
                if(resource.getCreateUserId() == user.getId()){
                    resource.setCreateUserName(user.getUsername());
                }
            }
        }

        return PageUtil.toPage(resourceList);
    }

    @Override
    public List<Resource> queryAll(ResourceQueryCriteria criteria){
        return resourceMapper.findAll(criteria);
    }

    //获取学校资源
    public PageResult<Resource> querySchoolResource(ResourceQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id",currentUser.getDeptId());
        List<User> userList = userMapper.selectList(queryWrapper);

        IPage<Resource> resourceList = resourceMapper.findAll(criteria, page);
        for(Resource resource:resourceList.getRecords()){
            for(User user:userList){
                if(resource.getCreateUserId() == user.getId()){
                    resource.setCreateUserName(user.getUsername());
                }
            }
        }
        return PageUtil.toPage(resourceList);
    }



    //获取教师自己创建的资源
    public PageResult<Resource> queryMyResource(ResourceQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());
        criteria.setCreateUserId(currentUser.getId());
        IPage<Resource> resourceList = resourceMapper.findAll(criteria, page);
        for(Resource resource:resourceList.getRecords()){
            resource.setCreateUserName(currentUserName);
        }
        return PageUtil.toPage(resourceList);
    }

    //获取公开的资源
    public PageResult<Resource> querySchoolPublicResource(ResourceQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());
        criteria.setIsOpen(1); //公开
//        criteria.setState(1); //发布
        return PageUtil.toPage(resourceMapper.findAll(criteria, page));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Resource resources) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        resources.setCreateUserId(currentUser.getId());
        if(teacher!=null && teacher.getId()!=null){
            resources.setCreateTeacherId(teacher.getId());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());
        resources.setCreateTime(timestamp);
        resources.setSchoolId(currentUser.getDeptId());
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Resource resources) {
        Resource resource = getById(resources.getId());
        resource.copy(resources);
        saveOrUpdate(resource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<String> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Resource> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Resource resource : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" name",  resource.getName());
            map.put(" type",  resource.getType());
            map.put(" resourcetypeid",  resource.getResourceTypeId());
            map.put(" createuserid",  resource.getCreateUserId());
            map.put(" createteacherid",  resource.getCreateTeacherId());
            map.put(" filenmae",  resource.getFileNmae());
            map.put(" tags",  resource.getTags());
            map.put(" tagids",  resource.getTagIds());
            map.put(" state",  resource.getState());
            map.put(" createtime",  resource.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}